<template>
  <div class="crktype-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :disabled="quickRange !== 'custom'" style="margin-left:12px;width:420px" />
      <el-select v-model="inTypeFilter" placeholder="入库类型" clearable style="width:160px;margin-left:12px">
        <el-option v-for="t in inboundTypes" :key="t" :label="t" :value="t" />
      </el-select>
      <el-select v-model="outTypeFilter" placeholder="出库类型" clearable style="width:160px;margin-left:12px">
        <el-option v-for="t in outboundTypes" :key="t" :label="t" :value="t" />
      </el-select>
      <el-button type="primary" style="margin-left:12px" @click="loadData()">生成报表</el-button>
    </div>

    <div class="charts">
      <div ref="inChart" class="chart"></div>
      <div ref="pieInChart" class="chart small"></div>
      <div ref="outChart" class="chart"></div>
      <div ref="pieOutChart" class="chart small"></div>
    </div>

  <div class="table-wrap">
    <el-table
      :data="detailData"
      border
      style="width:100%"
      height="520"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column type="index" label="序号" width="60" fixed="left" />
      <el-table-column label="货品信息" align="center" fixed="left">
        <el-table-column prop="goodsCode" label="货品编号" width="120" fixed="left" />
        <el-table-column prop="goodsName" label="货品名称" width="140" fixed="left" />
        <el-table-column prop="specs" label="规格型号" width="120" fixed="left" />
        <el-table-column prop="goodsType" label="货品类型" width="120" fixed="left" />
      </el-table-column>

      <el-table-column label="入库" align="center">
        <el-table-column label="进货入库" align="center">
          <el-table-column prop="in_purchase_qty" label="数量" width="90" />
          <el-table-column prop="in_purchase_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.in_purchase_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="生产入库" align="center">
          <el-table-column prop="in_product_qty" label="数量" width="90" />
          <el-table-column prop="in_product_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.in_product_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="退货入库" align="center">
          <el-table-column prop="in_return_qty" label="数量" width="90" />
          <el-table-column prop="in_return_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.in_return_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="盘盈入库" align="center">
          <el-table-column prop="in_profit_qty" label="数量" width="90" />
          <el-table-column prop="in_profit_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.in_profit_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="其他入库" align="center">
          <el-table-column prop="in_other_qty" label="数量" width="90" />
          <el-table-column prop="in_other_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.in_other_amt) }}</template>
          </el-table-column>
        </el-table-column>
      </el-table-column>

      <el-table-column label="出库" align="center">
        <el-table-column label="销售出库" align="center">
          <el-table-column prop="out_sale_qty" label="数量" width="90" />
          <el-table-column prop="out_sale_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.out_sale_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="调拨出库" align="center">
          <el-table-column prop="out_transfer_qty" label="数量" width="90" />
          <el-table-column prop="out_transfer_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.out_transfer_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="盘亏出库" align="center">
          <el-table-column prop="out_loss_qty" label="数量" width="90" />
          <el-table-column prop="out_loss_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.out_loss_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="退货出库" align="center">
          <el-table-column prop="out_return_qty" label="数量" width="90" />
          <el-table-column prop="out_return_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.out_return_amt) }}</template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="其他出库" align="center">
          <el-table-column prop="out_other_qty" label="数量" width="90" />
          <el-table-column prop="out_other_amt" label="金额" width="110">
            <template #default="{ row }">{{ formatMoney(row.out_other_amt) }}</template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ref, nextTick } from 'vue'
import { fetchInOutTypeSummary, fetchInOutTypeDetail } from '/@/api/report/crktype'

const quickRange = ref<'today'|'yesterday'|'week'|'month'|'custom'>('month')
const dateRange = ref<[string,string]|null>(null)
const inChart = ref<HTMLDivElement | null>(null)
const outChart = ref<HTMLDivElement | null>(null)
let inE: echarts.ECharts | null = null
let outE: echarts.ECharts | null = null
const detailData = ref<any[]>([])
const pieInChart = ref<HTMLDivElement | null>(null)
const pieOutChart = ref<HTMLDivElement | null>(null)
let pieInE: echarts.ECharts | null = null
let pieOutE: echarts.ECharts | null = null
const inboundTypes = ref<string[]>([])
const outboundTypes = ref<string[]>([])
const inTypeFilter = ref<string | undefined>()
const outTypeFilter = ref<string | undefined>()

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'today': return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': { const y = now.subtract(1,'day'); return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')] }
    case 'week': return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'month': return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    default: return dateRange.value ?? null
  }
}

async function loadData() {
  const range = computeRange()
  const res = await fetchInOutTypeSummary({ startTime: range?.[0], endTime: range?.[1] })
  // 支持三层 result：result.result.result，并兼容键名 inbound / out（或 outbound）
  const root = res?.data?.result?.result?.result ?? res?.data?.result?.result ?? res?.data?.result ?? res?.data ?? {}
  const inbound = root.inbound ?? root.Inbound ?? {}
  const outbound = root.out ?? root.Out ?? root.outbound ?? {}
  await nextTick()
  if (!inE) inE = echarts.init(inChart.value as HTMLDivElement)
  if (!outE) outE = echarts.init(outChart.value as HTMLDivElement)
  // 过滤类型（仅图表层面）
  const fInIdx = inTypeFilter.value ? (inbound.types || []).findIndex((x: string) => x === inTypeFilter.value) : -1
  const fOutIdx = outTypeFilter.value ? (outbound.types || []).findIndex((x: string) => x === outTypeFilter.value) : -1
  const inTypes = fInIdx >= 0 ? [inbound.types[fInIdx]] : (inbound.types || [])
  const inQty = fInIdx >= 0 ? [inbound.qty[fInIdx]] : (inbound.qty || [])
  const inRate = fInIdx >= 0 ? [inbound.rate[fInIdx]] : (inbound.rate || [])
  const outTypes = fOutIdx >= 0 ? [outbound.types[fOutIdx]] : (outbound.types || [])
  const outQty = fOutIdx >= 0 ? [outbound.qty[fOutIdx]] : (outbound.qty || [])
  const outRate = fOutIdx >= 0 ? [outbound.rate[fOutIdx]] : (outbound.rate || [])

  const inOpt: echarts.EChartsOption = {
    title: { text: '入库类型汇总', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: inTypes },
    yAxis: { type: 'value' },
    series: [ { type: 'bar', data: inQty } ],
    dataset: undefined,
  }
  const outOpt: echarts.EChartsOption = {
    title: { text: '出库类型汇总', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: outTypes },
    yAxis: { type: 'value' },
    series: [ { type: 'bar', data: outQty } ],
  }
  inE.setOption(inOpt)
  outE.setOption(outOpt)

  // 饼图（占比）
  if (!pieInE) pieInE = echarts.init(pieInChart.value as HTMLDivElement)
  if (!pieOutE) pieOutE = echarts.init(pieOutChart.value as HTMLDivElement)
  const pieInData = inTypes.map((t: string, i: number) => ({ name: t, value: inRate[i] }))
  const pieOutData = outTypes.map((t: string, i: number) => ({ name: t, value: outRate[i] }))
  pieInE.setOption({
    title: { text: '入库类型占比（%）', left: 'center' },
    tooltip: { trigger: 'item', formatter: '{b}: {c}%' },
    series: [{ type: 'pie', radius: '60%', data: pieInData, label: { formatter: '{b}: {c}%'} }]
  })
  pieOutE.setOption({
    title: { text: '出库类型占比（%）', left: 'center' },
    tooltip: { trigger: 'item', formatter: '{b}: {c}%' },
    series: [{ type: 'pie', radius: '60%', data: pieOutData, label: { formatter: '{b}: {c}%'} }]
  })

  // 生成类型筛选选项
  inboundTypes.value = inbound?.types || []
  outboundTypes.value = outbound?.types || []

  // 明细表
  const dres = await fetchInOutTypeDetail({ startTime: range?.[0], endTime: range?.[1], page: 1, pageSize: 10 })
  // 按要求：表格从 result.result.result.items 读取，向下兼容
  const droot = dres?.data?.result?.result?.result ?? dres?.data?.result?.result ?? dres?.data?.result ?? dres?.data ?? {}
  detailData.value = droot.items || []
}

function onQuickRange() { if (quickRange.value !== 'custom') dateRange.value = null; loadData() }

loadData()

function formatMoney(n: number) { return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0) }

function getSummaries(params: { columns: any[]; data: any[] }) {
  const { columns, data } = params
  const sums: (string | number)[] = []
  columns.forEach((col, index) => {
    if (index === 0) { sums[index] = '合计'; return }
    // 只对数值列进行求和
    const values = data.map((item: any) => Number(item[col.property]) || 0)
    if (!values.length || isNaN(values[0])) { sums[index] = '' } else { sums[index] = values.reduce((a, b) => a + b, 0) }
  })
  return sums
}
</script>

<style scoped>
.crktype-report { padding: 12px; }
.toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.charts { display: grid; grid-template-columns: 1fr; gap: 12px; }
.chart { width: 100%; height: 360px; background: #fff; border-radius: 4px; }
</style>


